# -*-coding: utf-8 -*-
"""
    @Theme   : Send Email
    @Time    : 2024/4/12 10:16
    @Author  : YamFish
    @Url     : https://www.zhihu.com/people/yamfish
"""
from threading import Thread

from flask import current_app, render_template
from flask_mail import Message

from suzyblog.extensions import mail


def _send_mail_with_context(app, message):
    with app.app_context():
        mail.send(message)


def send_mail(subject, to, content):
    app = current_app._get_current_object()
    message = Message(subject, recipients=[to], html=content)
    thr = Thread(target=_send_mail_with_context, args=(app, message))
    thr.start()
    return thr


def mail_new_comment(post):
    """send email to Admin"""
    html = render_template('blog/email.html', reply=False, post=post)
    send_mail(subject='New Comment', to=current_app.config['BLOG_EMAIL'], content=html)


def mail_new_reply(comment):
    """send email to the author of comment"""
    html = render_template('blog/email.html', reply=True, comment=comment)
    send_mail(subject='New Reply', to=comment.email, content=html)

